#include "logger.h"
#include "lockqueue.h"

#include <iostream>
#include <string>
#include <time.h>

Logger &Logger::GetInstance()
{
    static Logger logger;
    return logger;
}

Logger::Logger()
{
    // 创建并启动写日志线程
    // 这个线程主要负责磁盘IO的，与我们的业务分离，从而提高业务的运行效率
    std::thread writeThread([&]()
                            {
        for(;;)
        {
            time_t now = time(nullptr);
            tm *nowTime = localtime(&now);

            char file_name[128];
            sprintf(file_name, "%d-%d-%d-log.txt", nowTime->tm_year + 1900, nowTime->tm_mon + 1, nowTime->tm_mday);
            FILE *pf = fopen(file_name, "a+");
            if(pf == nullptr)
            {
                std::cout << "logger file : " << file_name << "open error!\n";
                exit(EXIT_FAILURE);
            }

            std::string msg = m_lockqueue.Pop();
            msg += '\n';
            fputs(msg.c_str(), pf);
            fclose(pf);
        } });

    // 设置线程分离，相当于是一个守护进程
    writeThread.detach();
}

// 设置日志级别
void Logger::SetLogLevel(LogLevel level)
{
    m_logLevel = level;
}

// 往日志队列里写数据
void Logger::Log(const std::string &msg)
{
    m_lockqueue.Push(msg);
}

LogLevel Logger::GetLogLevel()
{
    return m_logLevel;
}

std::string Logger::LevelToStr()
{
    if(m_logLevel == INFO)
        return "INFO";
    else if(m_logLevel == ERROR)
        return "ERROR";
    else if(m_logLevel == FATAL)
        return "FATAL";

    return "";
}
